// src/utils/http.ts
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';

// 创建axios实例
const service: AxiosInstance = axios.create({
	baseURL: import.meta.env.VITE_API_URL, // API的base_url
	timeout: 15000, // 请求超时时间
	headers: {
		'Content-Type': 'application/json;charset=utf-8',
	},
});

// 请求拦截器
service.interceptors.request.use(
	(config) => {
		// 可以在这里添加token等认证信息
		const token = localStorage.getItem('token');
		if (token) {
			config.headers['Authorization'] = `Bearer ${token}`;
		}
		return config;
	},
	(error) => {
		console.error('Request error:', error);
		return Promise.reject(error);
	}
);

// 响应拦截器
service.interceptors.response.use(
	(response: AxiosResponse) => {
		const res = response.data;

		// 如果是文件下载，直接返回response
		if (response.config.responseType === 'blob') {
			return res;
		}

		// 这里可以根据后端的响应格式进行适当的处理
		if (res.code !== 200) {
			ElMessage.error(res.message || '请求失败');
			return Promise.reject(new Error(res.message || '请求失败'));
		}

		return res;
	},
	(error) => {
		console.error('Response error:', error);
		ElMessage.error(error.message || '请求失败');
		return Promise.reject(error);
	}
);

// 封装请求方法
export const http = {
	get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
		return service.get(url, config);
	},

	post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
		return service.post(url, data, config);
	},

	put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
		return service.put(url, data, config);
	},

	delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
		return service.delete(url, config);
	},
};

export default service;
